package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sc.nft.dao.*;
import com.sc.nft.dto.DrawPrizeDTO;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.ListDetailsListDTO;
import com.sc.nft.entity.dto.UserIndependentListDTO;
import com.sc.nft.entity.vo.*;
import com.sc.nft.enums.*;
import com.sc.nft.enums.task.DrawPriceTypeEnum;
import com.sc.nft.enums.task.TaskPrizeTypeEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.MallRankingListPoolService;
import com.sc.nft.service.RankingBoardDetailsNumberService;
import com.sc.nft.service.TaskService;
import com.sc.nft.service.UserWalletService;
import com.sc.nft.util.BigDecimalUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

@Slf4j
@RequiredArgsConstructor
@Service
public class RankingBoardDetailsNumberServiceImpl implements RankingBoardDetailsNumberService {

    private final RankingBoardDetailsNumberDao rankingBoardDetailsNumberDao;

    private final RankingBoardConfDao rankingBoardConfDao;

    private final UserCollectionDao userCollectionDao;

    private final RankingBoardIncomeConfDao rankingBoardIncomeConfDao;

    private final RankingBoardRewardsConfDao rankingBoardRewardsConfDao;

    private final UserInfoDao userInfoDao;

    private final IdcardInfoDao idcardInfoDao;

    private final MallOrderDao mallOrderDao;

    private final FilterIncomeListDao filterIncomeListDao;

    private final UserWalletService userWalletService;

    private final TaskService taskService;
    private final UserWalletDao userWalletDao;
    private final UserWalletDetailDao userWalletDetailDao;
    private final ExpenditureRecordDao expenditureRecordDao;

    private final MallRankingListPoolService mallRankingListPoolService;

    @Override
    public IPage<ListDetailsListVO> listDetailsList(ListDetailsListDTO listDetailsListDTO) {
        /*
         * 1.根据规则获取表名
         * 2.根据表名获取数据
         * 3.如果获取不到数据,则翻转获取另外一个表的数据
         * 4.如果还是获取不到数据,则返回空
         */
        RankingBoardConf rankingBoardConf = rankingBoardConfDao.getById(listDetailsListDTO.getId());
        if (BeanUtil.isEmpty(rankingBoardConf)) {
            throw new GlobalRunTimeException("榜单不存在");
        }
        // 如果rankingBoardConfDao的结束时间小于当前时间,那么使用历史表进行查询
        if (listDetailsListDTO.getType().equals(1)) {
            if (rankingBoardConf.getEndTime().getTime() < new Date().getTime()) {
                IPage<ListDetailsListVO> sc_ranking_board_history_details = rankingBoardDetailsNumberDao.listDetailsList(listDetailsListDTO, "sc_ranking_board_history_details");
                if (CollUtil.isNotEmpty(sc_ranking_board_history_details.getRecords())) {
                    return sc_ranking_board_history_details;
                }
            }
        }
        IPage<ListDetailsListVO> listDetailsListVOIPage;
        listDetailsListVOIPage = rankingBoardDetailsNumberDao.listDetailsList(listDetailsListDTO, tableSegmentation(false));
        List<ListDetailsListVO> records = listDetailsListVOIPage.getRecords();
        // 正常的获取如果无法获取到数据,那么则翻转获取另外一个表的数据
        if (CollUtil.isEmpty(records)) {
            listDetailsListVOIPage = rankingBoardDetailsNumberDao.listDetailsList(listDetailsListDTO, tableSegmentation(true));
        }
        return listDetailsListVOIPage;
    }

    @Override
    public UserIndependentListVO userIndependentList(UserIndependentListDTO userIndependentListDTO, UserInfo userInfo) {
        /*
         * 1.查询榜单中的用户是否存在
         * 2.如果存在,则查询用户的排名,并且和上一个排名进行比较,看他差了多少持仓or额度
         * 3.如果不存在,查询用户的持仓.并且和最后一个做比较.看他差了多少持仓or额度
         */
        UserIndependentListVO userIndependentListVO = new UserIndependentListVO();
        ListDetailsListVO listDetailsListVO = listDetailsListByUserId(userIndependentListDTO.getId(), userInfo.getId());
        if (BeanUtil.isNotEmpty(listDetailsListVO)) {
            RankingBoardConf rankingBoardConf = rankingBoardConfDao.getById(userIndependentListDTO.getId());
            if (BeanUtil.isEmpty(rankingBoardConf)) {
                throw new GlobalRunTimeException("榜单不存在");
            }
            userIndependentListVO.setNickName(listDetailsListVO.getNickName());
            userIndependentListVO.setAvatarImg(listDetailsListVO.getAvatarImg());
            userIndependentListVO.setRanking(listDetailsListVO.getRanking());
            // 根据藏品id+用户id获取用户持仓
            if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.POSITION_RANKING)) {
                userIndependentListVO.setHoldCount(Convert.toStr(userCollectionDao.getByUserIdAndCollectionIdCount(userInfo.getId(), rankingBoardConf.getLinkCollectionId())));
            } else if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.IP_MALL_TRADING)) {
                userIndependentListVO.setHoldCount(Convert.toStr(mallOrderDao.getByUserIdSum(userInfo.getId(), rankingBoardConf.getBeginTime(), rankingBoardConf.getEndTime())));
            }else if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.NEW_POSITION_RANKING)) {
                userIndependentListVO.setHoldCount(Convert.toStr(userCollectionDao.getByUserIdAndCollectionIdCountGetTime(userInfo.getId(), rankingBoardConf.getLinkCollectionId(),rankingBoardConf.getBeginTime(),rankingBoardConf.getEndTime())));
            }
            return userIndependentListVO;
        } else {
            // 根据用户id,查询这个用户的持仓
            RankingBoardConf rankingBoardConf = rankingBoardConfDao.getById(userIndependentListDTO.getId());
            if (BeanUtil.isEmpty(rankingBoardConf)) {
                throw new GlobalRunTimeException("榜单不存在");
            }
            userIndependentListVO.setNickName(userInfo.getNickName());
            userIndependentListVO.setAvatarImg(userInfo.getAvatarImg());
            userIndependentListVO.setRanking(0);
            // 根据藏品id+用户id获取用户持仓
            if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.POSITION_RANKING)) {
                userIndependentListVO.setHoldCount(Convert.toStr(userCollectionDao.getByUserIdAndCollectionIdCount(userInfo.getId(), rankingBoardConf.getLinkCollectionId())));
            } else if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.IP_MALL_TRADING)) {
                userIndependentListVO.setHoldCount(Convert.toStr(mallOrderDao.getByUserIdSum(userInfo.getId(), rankingBoardConf.getBeginTime(), rankingBoardConf.getEndTime())));
            }else if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.NEW_POSITION_RANKING)) {
                userIndependentListVO.setHoldCount(Convert.toStr(userCollectionDao.getByUserIdAndCollectionIdCountGetTime(userInfo.getId(), rankingBoardConf.getLinkCollectionId(),rankingBoardConf.getBeginTime(),rankingBoardConf.getEndTime())));
            }
            return userIndependentListVO;
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rankingUpdate(RankingBoardConf rankingBoardConf) {
        // 根据rankingBoardConf的配置,来更新榜单.
        // 所有的藏品or用户的交易排行榜,出现相同的.都统一拿最后一条最新的数据,谁先谁前.
        if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.POSITION_RANKING)) {
            // 藏品持仓排行榜
            collectionListRanking(rankingBoardConf);
        } else if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.IP_MALL_TRADING)) {
            // 商城交易排行榜
            mallRanking(rankingBoardConf);
        } else if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.NEW_POSITION_RANKING)) {
            newCollectionListRanking(rankingBoardConf);
        }

    }
    private void newCollectionListRanking(RankingBoardConf rankingBoardConf) {
        // 藏品id.
        Long linkCollectionId = rankingBoardConf.getLinkCollectionId();
        // 最小持仓数量
        Integer minimumQuantity = rankingBoardConf.getMinimumQuantity();
        // 榜单人数
        Integer listNumber = rankingBoardConf.getListNumber();

        // 排名
        List<RanKingVO> ranKing = rankingBoardConfDao.getNewRanKing(rankingBoardConf.getBeginTime(),rankingBoardConf.getEndTime(),linkCollectionId, minimumQuantity, listNumber, rankingBoardConf.getId());
        // 根据排名把奖励给查出来,有可能会有多个,每个排名都要查询两次.
        List<RankingBoardDetailsEvenNumber> rankingBoardDetailsEvenNumbers = new ArrayList<>();
        for (RanKingVO ranKingVO : ranKing) {
            UserInfo userInfo = userInfoDao.getById(ranKingVO.getUserId());
            RankingBoardDetailsEvenNumber rankingBoardDetailsEvenNumber = new RankingBoardDetailsEvenNumber();
            rankingBoardDetailsEvenNumber.setRankingBoardConfId(rankingBoardConf.getId());
            rankingBoardDetailsEvenNumber.setType(rankingBoardConf.getType());
            rankingBoardDetailsEvenNumber.setName(rankingBoardConf.getName());
            rankingBoardDetailsEvenNumber.setUserId(ranKingVO.getUserId());
            rankingBoardDetailsEvenNumber.setCollectionId(rankingBoardConf.getLinkCollectionId());
            rankingBoardDetailsEvenNumber.setCollectionName(rankingBoardConf.getLinkColectionName());
            rankingBoardDetailsEvenNumber.setRanking(ranKingVO.getRanks());
            rankingBoardDetailsEvenNumber.setHoldCount(Convert.toStr(ranKingVO.getCount()));
            rankingBoardDetailsEvenNumber.setStatus(RankingBoardIncomeAndRewardsStatusEnum.UNISSUED);
            if (BeanUtil.isNotEmpty(userInfo)) {
                rankingBoardDetailsEvenNumber.setUserTel(userInfo.getUserTel());
                rankingBoardDetailsEvenNumber.setAvatarImg(userInfo.getAvatarImg());
                rankingBoardDetailsEvenNumber.setNickName(userInfo.getNickName());
                IdcardInfo byUserIdAndIsPass = idcardInfoDao.getByUserIdAndIsPass(userInfo.getId());
                if (BeanUtil.isNotEmpty(byUserIdAndIsPass)) {
                    rankingBoardDetailsEvenNumber.setIdcardName(byUserIdAndIsPass.getName());
                }
            }

            // 把数据插入集合中,插入之前需要把另外一个表中的数据删除掉.
            rankingBoardDetailsEvenNumbers.add(rankingBoardDetailsEvenNumber);
        }
        if (CollUtil.isNotEmpty(rankingBoardDetailsEvenNumbers)) {
            batchOperation(rankingBoardConf, rankingBoardDetailsEvenNumbers);
        }
        rankingBoardConfDao.updateModifyTime(rankingBoardConf.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void settlementList(RankingBoardConf rankingBoardConf) {
        if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.POSITION_RANKING)) {
            positionListSettlement(rankingBoardConf);
        } else if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.IP_MALL_TRADING)) {
            mallListSettlement(rankingBoardConf);
        } else if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.NEW_POSITION_RANKING)) {
            newPositionListSettlement(rankingBoardConf);
        }

    }
    private void newPositionListSettlement(RankingBoardConf rankingBoardConf) {
        // 榜单定榜,把所有的用户写入到历史表并且等待结算.
        // 藏品id.
        Long linkCollectionId = rankingBoardConf.getLinkCollectionId();
        // 最小持仓数量
        Integer minimumQuantity = rankingBoardConf.getMinimumQuantity();
        // 榜单人数
        Integer listNumber = rankingBoardConf.getListNumber();
        // 排名
        List<RanKingVO> ranKing = rankingBoardConfDao.getNewRanKing(rankingBoardConf.getBeginTime(),rankingBoardConf.getEndTime(),linkCollectionId, minimumQuantity, listNumber, rankingBoardConf.getId());
        // 根据排名把奖励给查出来,有可能会有多个,每个排名都要查询两次.
        BigDecimal needSub = BigDecimal.ZERO;
        List<RankingBoardDetailsEvenNumber> rankingBoardDetailsEvenNumbers = new ArrayList<>();
        for (RanKingVO ranKingVO : ranKing) {
            UserInfo userInfo = userInfoDao.getById(ranKingVO.getUserId());
            RankingBoardDetailsEvenNumber rankingBoardDetailsEvenNumber = new RankingBoardDetailsEvenNumber();
            rankingBoardDetailsEvenNumber.setRankingBoardConfId(rankingBoardConf.getId());
            rankingBoardDetailsEvenNumber.setType(rankingBoardConf.getType());
            rankingBoardDetailsEvenNumber.setName(rankingBoardConf.getName());
            rankingBoardDetailsEvenNumber.setUserId(ranKingVO.getUserId());
            rankingBoardDetailsEvenNumber.setCollectionId(rankingBoardConf.getLinkCollectionId());
            rankingBoardDetailsEvenNumber.setCollectionName(rankingBoardConf.getLinkColectionName());
            rankingBoardDetailsEvenNumber.setRanking(ranKingVO.getRanks());
            rankingBoardDetailsEvenNumber.setHoldCount(Convert.toStr(ranKingVO.getCount()));
            rankingBoardDetailsEvenNumber.setUserTel(BeanUtil.isNotEmpty(userInfo) ? userInfo.getUserTel() : null);
            // 发放时间设置到第二天晚上9点钟
            Date grantTime = DateUtil.offsetDay(DateUtil.endOfDay(rankingBoardConf.getEndTime()), 1);
            grantTime.setHours(20);
            grantTime.setMinutes(0);
            grantTime.setSeconds(0);
            rankingBoardDetailsEvenNumber.setGrantTime(grantTime);
            rankingBoardDetailsEvenNumber.setAvatarImg(BeanUtil.isNotEmpty(userInfo) ? userInfo.getAvatarImg() : null);
            rankingBoardDetailsEvenNumber.setNickName(BeanUtil.isNotEmpty(userInfo) ? userInfo.getNickName() : null);
            IdcardInfo byUserIdAndIsPass = idcardInfoDao.getByUserIdAndIsPass(BeanUtil.isNotEmpty(userInfo) ? userInfo.getId() : null);
            RankingBonusBillVO rankingBonusBillVO = rankingBonusBill(rankingBoardDetailsEvenNumber, rankingBoardConf);
            rankingBoardDetailsEvenNumber.setRewardsDetails(rankingBonusBillVO.getLinkName());
            rankingBoardDetailsEvenNumber.setIncomeName(rankingBonusBillVO.getIncomeName());
            rankingBoardDetailsEvenNumber.setIncomeAmount(Convert.toStr(rankingBonusBillVO.getAmount()));
            rankingBoardDetailsEvenNumber.setIncomeConfId(rankingBonusBillVO.getIncomeConfId());
            rankingBoardDetailsEvenNumber.setRewardsConfId(rankingBonusBillVO.getRewardsConfId());
            Integer status = rankingBonusBillVO.getStatus();
            // 这个地方需要判定是否给奖励 如果为1则代表市值账号,直接给拦截掉.
            if (status.equals(1)) {
                rankingBoardDetailsEvenNumber.setStatus(RankingBoardIncomeAndRewardsStatusEnum.INTERCEPTED);
            } else {
                rankingBoardDetailsEvenNumber.setStatus(RankingBoardIncomeAndRewardsStatusEnum.UNISSUED);
            }
            if (BeanUtil.isNotEmpty(byUserIdAndIsPass)) {
                rankingBoardDetailsEvenNumber.setIdcardName(byUserIdAndIsPass.getName());
            }
            // 把数据插入集合中,插入之前需要把另外一个表中的数据删除掉.
            rankingBoardDetailsEvenNumbers.add(rankingBoardDetailsEvenNumber);
            needSub = BigDecimalUtils.add(needSub,rankingBonusBillVO.getAmount());
        }
        // 清空两个表中的数据
        rankingBoardDetailsNumberDao.deleteOddnumberedTable(rankingBoardConf.getId());
        rankingBoardDetailsNumberDao.deleteEvenTable(rankingBoardConf.getId());
        // 插入表,插入之前删除另外一张表的数据
        if (CollUtil.isNotEmpty(rankingBoardDetailsEvenNumbers)) {
            rankingBoardDetailsNumberDao.saveBath(rankingBoardDetailsEvenNumbers, "sc_ranking_board_history_details");
            // 排行榜池 减少金额
            mallRankingListPoolService.subAmount(needSub);
        }
        rankingBoardConfDao.updateIsSettlement(rankingBoardConf.getId());
    }

    private void mallListSettlement(RankingBoardConf rankingBoardConf) {
        // 榜单定榜,把所有的用户写入到历史表并且等待结算.
        Integer minimumQuantity = rankingBoardConf.getMinimumQuantity();
        // 榜单人数
        Integer listNumber = rankingBoardConf.getListNumber();

        // 开始时间
        Date startTime = rankingBoardConf.getBeginTime();
        // 结束时间
        Date endTime = rankingBoardConf.getEndTime();
        List<RankingBoardDetailsEvenNumber> rankingBoardDetailsEvenNumbers = new ArrayList<>();
        List<MallRanking> ranKing = rankingBoardConfDao.mallRanking(startTime, endTime, listNumber, minimumQuantity, rankingBoardConf.getId());
        // 根据排名把奖励给查出来,有可能会有多个,每个排名都要查询两次.
        BigDecimal needSub = BigDecimal.ZERO;
        for (MallRanking ranKingVO : ranKing) {
            UserInfo userInfo = userInfoDao.getById(ranKingVO.getUserId());
            RankingBoardDetailsEvenNumber rankingBoardDetailsEvenNumber = new RankingBoardDetailsEvenNumber();
            rankingBoardDetailsEvenNumber.setRankingBoardConfId(rankingBoardConf.getId());
            rankingBoardDetailsEvenNumber.setType(rankingBoardConf.getType());
            rankingBoardDetailsEvenNumber.setName(rankingBoardConf.getName());
            rankingBoardDetailsEvenNumber.setUserId(ranKingVO.getUserId());
            rankingBoardDetailsEvenNumber.setCollectionId(rankingBoardConf.getLinkCollectionId());
            rankingBoardDetailsEvenNumber.setCollectionName(rankingBoardConf.getLinkColectionName());
            rankingBoardDetailsEvenNumber.setRanking(ranKingVO.getRanks());
            rankingBoardDetailsEvenNumber.setHoldCount(Convert.toStr(ranKingVO.getTotalRealPrice()));
            rankingBoardDetailsEvenNumber.setUserTel(BeanUtil.isNotEmpty(userInfo) ? userInfo.getUserTel() : null);
            // 发放时间设置到第二天晚上9点钟
            Date grantTime = DateUtil.offsetDay(DateUtil.endOfDay(rankingBoardConf.getEndTime()), 1);
            grantTime.setHours(20);
            grantTime.setMinutes(0);
            grantTime.setSeconds(0);
            rankingBoardDetailsEvenNumber.setGrantTime(grantTime);
            rankingBoardDetailsEvenNumber.setAvatarImg(BeanUtil.isNotEmpty(userInfo) ? userInfo.getAvatarImg() : null);
            rankingBoardDetailsEvenNumber.setNickName(BeanUtil.isNotEmpty(userInfo) ? userInfo.getNickName() : null);
            IdcardInfo byUserIdAndIsPass = idcardInfoDao.getByUserIdAndIsPass(BeanUtil.isNotEmpty(userInfo) ? userInfo.getId() : null);
            RankingBonusBillVO rankingBonusBillVO = rankingBonusBill(rankingBoardDetailsEvenNumber, rankingBoardConf);
            rankingBoardDetailsEvenNumber.setRewardsDetails(rankingBonusBillVO.getLinkName());
            rankingBoardDetailsEvenNumber.setIncomeName(rankingBonusBillVO.getIncomeName());
            rankingBoardDetailsEvenNumber.setIncomeAmount(Convert.toStr(rankingBonusBillVO.getAmount()));
            rankingBoardDetailsEvenNumber.setIncomeConfId(rankingBonusBillVO.getIncomeConfId());
            rankingBoardDetailsEvenNumber.setRewardsConfId(rankingBonusBillVO.getRewardsConfId());
            Integer status = rankingBonusBillVO.getStatus();
            // 这个地方需要判定是否给奖励 如果为1则代表市值账号,直接给拦截掉.
            if (status.equals(1)) {
                rankingBoardDetailsEvenNumber.setStatus(RankingBoardIncomeAndRewardsStatusEnum.INTERCEPTED);
            } else {
                rankingBoardDetailsEvenNumber.setStatus(RankingBoardIncomeAndRewardsStatusEnum.UNISSUED);
            }
            if (BeanUtil.isNotEmpty(byUserIdAndIsPass)) {
                rankingBoardDetailsEvenNumber.setIdcardName(byUserIdAndIsPass.getName());
            }
            // 把数据插入集合中,插入之前需要把另外一个表中的数据删除掉.
            rankingBoardDetailsEvenNumbers.add(rankingBoardDetailsEvenNumber);
            needSub = BigDecimalUtils.add(needSub,rankingBonusBillVO.getAmount());
        }
        // 清空两个表中的数据
        rankingBoardDetailsNumberDao.deleteOddnumberedTable(rankingBoardConf.getId());
        rankingBoardDetailsNumberDao.deleteEvenTable(rankingBoardConf.getId());
        // 插入表,插入之前删除另外一张表的数据
        if (CollUtil.isNotEmpty(rankingBoardDetailsEvenNumbers)) {
            rankingBoardDetailsNumberDao.saveBath(rankingBoardDetailsEvenNumbers, "sc_ranking_board_history_details");
            // 排行榜池 减少金额
            mallRankingListPoolService.subAmount(needSub);
        }
        rankingBoardConfDao.updateIsSettlement(rankingBoardConf.getId());
    }

    private void positionListSettlement(RankingBoardConf rankingBoardConf) {
        // 榜单定榜,把所有的用户写入到历史表并且等待结算.
        // 藏品id.
        Long linkCollectionId = rankingBoardConf.getLinkCollectionId();
        // 最小持仓数量
        Integer minimumQuantity = rankingBoardConf.getMinimumQuantity();
        // 榜单人数
        Integer listNumber = rankingBoardConf.getListNumber();
        // 排名
        List<RanKingVO> ranKing = rankingBoardConfDao.getRanKing(linkCollectionId, minimumQuantity, listNumber, rankingBoardConf.getId());
        // 根据排名把奖励给查出来,有可能会有多个,每个排名都要查询两次.
        BigDecimal needSub = BigDecimal.ZERO;
        List<RankingBoardDetailsEvenNumber> rankingBoardDetailsEvenNumbers = new ArrayList<>();
        for (RanKingVO ranKingVO : ranKing) {
            UserInfo userInfo = userInfoDao.getById(ranKingVO.getUserId());
            RankingBoardDetailsEvenNumber rankingBoardDetailsEvenNumber = new RankingBoardDetailsEvenNumber();
            rankingBoardDetailsEvenNumber.setRankingBoardConfId(rankingBoardConf.getId());
            rankingBoardDetailsEvenNumber.setType(rankingBoardConf.getType());
            rankingBoardDetailsEvenNumber.setName(rankingBoardConf.getName());
            rankingBoardDetailsEvenNumber.setUserId(ranKingVO.getUserId());
            rankingBoardDetailsEvenNumber.setCollectionId(rankingBoardConf.getLinkCollectionId());
            rankingBoardDetailsEvenNumber.setCollectionName(rankingBoardConf.getLinkColectionName());
            rankingBoardDetailsEvenNumber.setRanking(ranKingVO.getRanks());
            rankingBoardDetailsEvenNumber.setHoldCount(Convert.toStr(ranKingVO.getCount()));
            rankingBoardDetailsEvenNumber.setUserTel(BeanUtil.isNotEmpty(userInfo) ? userInfo.getUserTel() : null);
            // 发放时间设置到第二天晚上9点钟
            Date grantTime = DateUtil.offsetDay(DateUtil.endOfDay(rankingBoardConf.getEndTime()), 1);
            grantTime.setHours(20);
            grantTime.setMinutes(0);
            grantTime.setSeconds(0);
            rankingBoardDetailsEvenNumber.setGrantTime(grantTime);
            rankingBoardDetailsEvenNumber.setAvatarImg(BeanUtil.isNotEmpty(userInfo) ? userInfo.getAvatarImg() : null);
            rankingBoardDetailsEvenNumber.setNickName(BeanUtil.isNotEmpty(userInfo) ? userInfo.getNickName() : null);
            IdcardInfo byUserIdAndIsPass = idcardInfoDao.getByUserIdAndIsPass(BeanUtil.isNotEmpty(userInfo) ? userInfo.getId() : null);
            RankingBonusBillVO rankingBonusBillVO = rankingBonusBill(rankingBoardDetailsEvenNumber, rankingBoardConf);
            rankingBoardDetailsEvenNumber.setRewardsDetails(rankingBonusBillVO.getLinkName());
            rankingBoardDetailsEvenNumber.setIncomeName(rankingBonusBillVO.getIncomeName());
            rankingBoardDetailsEvenNumber.setIncomeAmount(Convert.toStr(rankingBonusBillVO.getAmount()));
            rankingBoardDetailsEvenNumber.setIncomeConfId(rankingBonusBillVO.getIncomeConfId());
            rankingBoardDetailsEvenNumber.setRewardsConfId(rankingBonusBillVO.getRewardsConfId());
            Integer status = rankingBonusBillVO.getStatus();
            // 这个地方需要判定是否给奖励 如果为1则代表市值账号,直接给拦截掉.
            if (status.equals(1)) {
                rankingBoardDetailsEvenNumber.setStatus(RankingBoardIncomeAndRewardsStatusEnum.INTERCEPTED);
            } else {
                rankingBoardDetailsEvenNumber.setStatus(RankingBoardIncomeAndRewardsStatusEnum.UNISSUED);
            }
            if (BeanUtil.isNotEmpty(byUserIdAndIsPass)) {
                rankingBoardDetailsEvenNumber.setIdcardName(byUserIdAndIsPass.getName());
            }
            // 把数据插入集合中,插入之前需要把另外一个表中的数据删除掉.
            rankingBoardDetailsEvenNumbers.add(rankingBoardDetailsEvenNumber);
            needSub = BigDecimalUtils.add(needSub,rankingBonusBillVO.getAmount());
        }
        // 清空两个表中的数据
        rankingBoardDetailsNumberDao.deleteOddnumberedTable(rankingBoardConf.getId());
        rankingBoardDetailsNumberDao.deleteEvenTable(rankingBoardConf.getId());
        // 插入表,插入之前删除另外一张表的数据
        if (CollUtil.isNotEmpty(rankingBoardDetailsEvenNumbers)) {
            rankingBoardDetailsNumberDao.saveBath(rankingBoardDetailsEvenNumbers, "sc_ranking_board_history_details");
            // 排行榜池 减少金额
            mallRankingListPoolService.subAmount(needSub);
        }
        rankingBoardConfDao.updateIsSettlement(rankingBoardConf.getId());
    }

    @Override
    public void rankingAward(RankingBoardHistoryDetails rankingBoardHistoryDetail) {
        /*
         根据定榜的数据.榜单id和用户的排行榜.来计算奖励.
         A用户交易激励收益 = IP商城订单利润 * 瓜分收益比例 * (A个人交易额/配置)

         */
        RankingBoardConf rankingBoardConf = rankingBoardConfDao.getById(rankingBoardHistoryDetail.getRankingBoardConfId());

        if (rankingBoardHistoryDetail.getType().equals(RankingBoardTypeEnum.POSITION_RANKING)) {
            listSettlement(rankingBoardHistoryDetail, rankingBoardConf);
        } else if (rankingBoardHistoryDetail.getType().equals(RankingBoardTypeEnum.IP_MALL_TRADING)) {
            ipMallListRewards(rankingBoardHistoryDetail, rankingBoardConf);
        } else if (rankingBoardHistoryDetail.getType().equals(RankingBoardTypeEnum.NEW_POSITION_RANKING)) {
            listSettlement(rankingBoardHistoryDetail, rankingBoardConf);
        }
    }

    private void ipMallListRewards(RankingBoardHistoryDetails rankingBoardHistoryDetail, RankingBoardConf rankingBoardConf) {
        MallRankingListPool rankingListPool = mallRankingListPoolService.getResidualPrizePool();
        if (rankingBoardConf.getIsOpenRewards()) {
            // 获取当前的排行榜,用户满足的条件.根据满足的条件来计算当前用户的收益.
            RankingBoardIncomeConf rankingBoardIncomeConf = rankingBoardIncomeConfDao.getByRankingBoardConfId(rankingBoardConf.getId(), rankingBoardHistoryDetail.getRanking());
            if (BeanUtil.isNotEmpty(rankingBoardIncomeConf)) {
                if (rankingBoardIncomeConf.getBeginSection() + 1 <= rankingBoardHistoryDetail.getRanking() && rankingBoardIncomeConf.getEndSection() >= rankingBoardHistoryDetail.getRanking()) {
                    // 分红
                    BigDecimal shareOutBonus = BigDecimalUtils.p(rankingBoardHistoryDetail.getIncomeAmount());
                    increaseTheBalance(rankingBoardHistoryDetail, rankingBoardConf, shareOutBonus);
                    mallRankingListPoolService.subFreezeAmount(shareOutBonus);
                    UserRankingBoardIncomeLog userRankingBoardIncomeLog = new UserRankingBoardIncomeLog();
                    userRankingBoardIncomeLog.setRankingBoardConfId(rankingBoardConf.getId());
                    userRankingBoardIncomeLog.setRankingBoardIncomeId(rankingBoardIncomeConf.getId());
                    userRankingBoardIncomeLog.setRanking(rankingBoardHistoryDetail.getRanking());
                    userRankingBoardIncomeLog.setUserId(rankingBoardHistoryDetail.getUserId());
                    userRankingBoardIncomeLog.setHoldCount(rankingBoardHistoryDetail.getHoldCount());
                    userRankingBoardIncomeLog.setAmount(shareOutBonus);
                    userRankingBoardIncomeLog.setIncomeName(rankingBoardIncomeConf.getIncomeName());
                    userRankingBoardIncomeLog.setIncomeProportion(rankingBoardIncomeConf.getIncomeProportion());
                    userRankingBoardIncomeLog.setExpenditureRecordType(rankingBoardIncomeConf.getExpenditureRecordType().getCode());
                    userRankingBoardIncomeLog.setLinkConllectionId(rankingBoardConf.getLinkCollectionId());
                    userRankingBoardIncomeLog.setLinkConllectionName(rankingBoardConf.getLinkColectionName());
                    userRankingBoardIncomeLog.insert();
                }

            }

            // 交易激励收益,有可能会有多个的情况出现.
            List<RankingBoardRewardsConf> tradingIncentiveEarnings = rankingBoardRewardsConfDao.getTradingIncentiveEarnings(rankingBoardConf.getId(), rankingBoardHistoryDetail.getRanking());
            if (CollUtil.isNotEmpty(tradingIncentiveEarnings)) {
                if (CollUtil.isNotEmpty(tradingIncentiveEarnings)) {
                    List<DrawPrizeDTO> list = new ArrayList<>();
                    // 给当前用户循环发放奖励,奖励可能会有多个
                    tradingIncentiveEarnings.forEach(rankingBoardRewardsConf -> {
                        if (rankingBoardRewardsConf.getBeginSection() + 1 <= rankingBoardHistoryDetail.getRanking() && rankingBoardRewardsConf.getEndSection() >= rankingBoardHistoryDetail.getRanking()) {
                            DrawPrizeDTO drawPrizeDTO = new DrawPrizeDTO();
                            drawPrizeDTO.setPrizeType(TaskPrizeTypeEnum.getByCode(rankingBoardRewardsConf.getLinkType().getCode()));
                            drawPrizeDTO.setEquityId(rankingBoardRewardsConf.getLinkId());
                            drawPrizeDTO.setPrizeCount(rankingBoardRewardsConf.getLinkCount());
                            list.add(drawPrizeDTO);
                            UserRankingBoardRewardsLog userRankingBoardRewardsLog = new UserRankingBoardRewardsLog();
                            userRankingBoardRewardsLog.setRankingBoardConfId(rankingBoardConf.getId());
                            userRankingBoardRewardsLog.setRankingBoardRewardsId(rankingBoardRewardsConf.getId());
                            userRankingBoardRewardsLog.setUserId(rankingBoardHistoryDetail.getUserId());
                            userRankingBoardRewardsLog.setRanking(rankingBoardHistoryDetail.getRanking());
                            userRankingBoardRewardsLog.setLinkType(rankingBoardRewardsConf.getLinkType());
                            userRankingBoardRewardsLog.setLinkImage(rankingBoardRewardsConf.getLinkImage());
                            userRankingBoardRewardsLog.setLinkName(rankingBoardRewardsConf.getLinkName());
                            userRankingBoardRewardsLog.setLinkId(rankingBoardRewardsConf.getLinkId());
                            userRankingBoardRewardsLog.setLinkCount(rankingBoardRewardsConf.getLinkCount());
                            userRankingBoardRewardsLog.insert();
                        }

                    });
                    if (CollUtil.isNotEmpty(list)) {
                        taskService.addDrawPrize(rankingBoardHistoryDetail.getUserId(), rankingBoardHistoryDetail.getId(), rankingBoardHistoryDetail.getId(), rankingBoardHistoryDetail.getName(), list, DrawPriceTypeEnum.PLEDGE);
                    }
                }
            }
        }

        rankingBoardConfDao.closeAnAccount(rankingBoardConf.getId());
        rankingBoardHistoryDetail.setStatus(RankingBoardIncomeAndRewardsStatusEnum.ISSUED);
        rankingBoardHistoryDetail.updateById();
    }

    private void increaseTheBalance(RankingBoardHistoryDetails rankingBoardHistoryDetail, RankingBoardConf rankingBoardConf, BigDecimal shareOutBonus) {
        UserWallet userWallet = userWalletDao.getByUserId(rankingBoardHistoryDetail.getUserId());
        UserWalletDetail userWalletDetail = new UserWalletDetail();
        userWalletDetail.setUserId(rankingBoardHistoryDetail.getUserId());
        userWalletDetail.setType(WalletDetailTypeEnum.RANKING_BONUS);
        userWalletDetail.setAmount(NumberUtil.toBigDecimal(shareOutBonus));
        userWalletDetail.setCharge(BigDecimal.ZERO);
        userWalletDetail.setBalanceType(UserBalanceTypeEnum.PAY_BALANCE);
        userWalletDetail.setRealAmount(userWalletDetail.getAmount());
        userWalletDetail.setAfterBalance(userWallet.getPayBalance().add(userWalletDetail.getAmount()));
        userWalletDetail.setBeforeBalance(userWallet.getPayBalance());
        userWalletDetail.setIsAdd(Boolean.TRUE);
        userWalletDetailDao.insert(userWalletDetail);

        ExpenditureRecord expenditureRecord = new ExpenditureRecord();
        expenditureRecord.setUserId(rankingBoardHistoryDetail.getUserId());
        expenditureRecord.setAmount(userWalletDetail.getAmount());
        expenditureRecord.setCharge(BigDecimal.ZERO);
        expenditureRecord.setRealAmount(userWalletDetail.getAmount());
        expenditureRecord.setType(ExpenditureRecordTypeEnum.RED_PACKET);
        expenditureRecord.setBeforeBalance(userWalletDetail.getBeforeBalance());
        expenditureRecord.setAfterBalance(userWalletDetail.getAfterBalance());

        // “排行榜名称”+“名次”+激励红包
        expenditureRecord.setRemark(StrUtil.format("{}第{}名{}", rankingBoardConf.getName(), rankingBoardHistoryDetail.getRanking(), "激励MT原石"));
        expenditureRecordDao.insert(expenditureRecord);
        //加钱
        userWalletDao.addPayBalance(rankingBoardHistoryDetail.getUserId(), userWalletDetail.getAmount());
    }

    private void listSettlement(RankingBoardHistoryDetails rankingBoardHistoryDetail, RankingBoardConf rankingBoardConf) {
        // IP商城订单利润 * 瓜分收益比例 * (A持仓数量/前1-10名总持仓数量)
        // A用户排名激励收益(排名内) = IP商城订单利润 * 瓜分收益比例 * (A持仓数量/前10-50名总持仓数量)
        // A用户交易激励收益 = IP商城订单利润 * 瓜分收益比例 * (A团队交易额/前1-50名总交易额)
        // 获取ip商城订单利润
        MallRankingListPool rankingListPool = mallRankingListPoolService.getResidualPrizePool();
        if (rankingBoardConf.getIsOpenRewards()) {
            // 获取当前的排行榜,用户满足的条件.根据满足的条件来计算当前用户的收益.
            RankingBoardIncomeConf rankingBoardIncomeConf = rankingBoardIncomeConfDao.getByRankingBoardConfId(rankingBoardConf.getId(), rankingBoardHistoryDetail.getRanking());
            if (BeanUtil.isNotEmpty(rankingBoardIncomeConf)) {
                // 获取到了满足用户收益以后,获取这个区间的总持仓数量.
                if (rankingBoardIncomeConf.getBeginSection() + 1 <= rankingBoardHistoryDetail.getRanking() && rankingBoardIncomeConf.getEndSection() >= rankingBoardHistoryDetail.getRanking()) {
                    // 计算当前用户的收益.
                    BigDecimal earnings = BigDecimalUtils.p(rankingBoardHistoryDetail.getIncomeAmount());
                    // 发放的奖励,直接写入到账单里面.
                    if (NumberUtil.isGreater(earnings, Convert.toBigDecimal(0))) {
                        increaseTheBalance(rankingBoardHistoryDetail, rankingBoardConf, earnings);
                        mallRankingListPoolService.subFreezeAmount(earnings);
                        UserRankingBoardIncomeLog userRankingBoardIncomeLog = new UserRankingBoardIncomeLog();
                        userRankingBoardIncomeLog.setRankingBoardConfId(rankingBoardConf.getId());
                        userRankingBoardIncomeLog.setRankingBoardIncomeId(rankingBoardIncomeConf.getId());
                        userRankingBoardIncomeLog.setRanking(rankingBoardHistoryDetail.getRanking());
                        userRankingBoardIncomeLog.setUserId(rankingBoardHistoryDetail.getUserId());
                        userRankingBoardIncomeLog.setHoldCount(rankingBoardHistoryDetail.getHoldCount());
                        userRankingBoardIncomeLog.setAmount(earnings);
                        userRankingBoardIncomeLog.setIncomeName(rankingBoardIncomeConf.getIncomeName());
                        userRankingBoardIncomeLog.setIncomeProportion(rankingBoardIncomeConf.getIncomeProportion());
                        userRankingBoardIncomeLog.setExpenditureRecordType(rankingBoardIncomeConf.getExpenditureRecordType().getCode());
                        userRankingBoardIncomeLog.setLinkConllectionId(rankingBoardConf.getLinkCollectionId());
                        userRankingBoardIncomeLog.setLinkConllectionName(rankingBoardConf.getLinkColectionName());
                        userRankingBoardIncomeLog.insert();
                    }
                }
            }


            // 交易激励收益,有可能会有多个的情况出现.
            List<RankingBoardRewardsConf> tradingIncentiveEarnings = rankingBoardRewardsConfDao.getTradingIncentiveEarnings(rankingBoardConf.getId(), rankingBoardHistoryDetail.getRanking());
            if (CollUtil.isNotEmpty(tradingIncentiveEarnings)) {
                if (CollUtil.isNotEmpty(tradingIncentiveEarnings)) {
                    List<DrawPrizeDTO> list = new ArrayList<>();
                    // 给当前用户循环发放奖励,奖励可能会有多个
                    tradingIncentiveEarnings.forEach(rankingBoardRewardsConf -> {
                        if (rankingBoardRewardsConf.getBeginSection() + 1 <= rankingBoardHistoryDetail.getRanking() && rankingBoardRewardsConf.getEndSection() >= rankingBoardHistoryDetail.getRanking()) {
                            DrawPrizeDTO drawPrizeDTO = new DrawPrizeDTO();
                            drawPrizeDTO.setPrizeType(TaskPrizeTypeEnum.getByCode(rankingBoardRewardsConf.getLinkType().getCode()));
                            drawPrizeDTO.setEquityId(rankingBoardRewardsConf.getLinkId());
                            drawPrizeDTO.setPrizeCount(rankingBoardRewardsConf.getLinkCount());
                            list.add(drawPrizeDTO);
                            UserRankingBoardRewardsLog userRankingBoardRewardsLog = new UserRankingBoardRewardsLog();
                            userRankingBoardRewardsLog.setRankingBoardConfId(rankingBoardConf.getId());
                            userRankingBoardRewardsLog.setRankingBoardRewardsId(rankingBoardRewardsConf.getId());
                            userRankingBoardRewardsLog.setUserId(rankingBoardHistoryDetail.getUserId());
                            userRankingBoardRewardsLog.setRanking(rankingBoardHistoryDetail.getRanking());
                            userRankingBoardRewardsLog.setLinkType(rankingBoardRewardsConf.getLinkType());
                            userRankingBoardRewardsLog.setLinkImage(rankingBoardRewardsConf.getLinkImage());
                            userRankingBoardRewardsLog.setLinkName(rankingBoardRewardsConf.getLinkName());
                            userRankingBoardRewardsLog.setLinkId(rankingBoardRewardsConf.getLinkId());
                            userRankingBoardRewardsLog.setLinkCount(rankingBoardRewardsConf.getLinkCount());
                            userRankingBoardRewardsLog.insert();
                        }

                    });
                    if (CollUtil.isNotEmpty(list)) {
                        taskService.addDrawPrize(rankingBoardHistoryDetail.getUserId(), rankingBoardHistoryDetail.getId(), IdUtil.getSnowflakeNextId(), rankingBoardHistoryDetail.getName(), list, DrawPriceTypeEnum.PLEDGE);
                    }
                }
            }
        }
        rankingBoardHistoryDetail.setStatus(RankingBoardIncomeAndRewardsStatusEnum.ISSUED);
        rankingBoardHistoryDetail.updateById();
        rankingBoardConfDao.closeAnAccount(rankingBoardConf.getId());
    }


    /**
     * 当前分的钱.
     *
     * @param rankingBoardDetailsEvenNumber
     * @param rankingBoardConf
     * @return
     */
    private RankingBonusBillVO rankingBonusBill(RankingBoardDetailsEvenNumber rankingBoardDetailsEvenNumber, RankingBoardConf rankingBoardConf) {
        RankingBonusBillVO rankingBonusBillVO = new RankingBonusBillVO();
        // IP商城订单利润 * 瓜分收益比例 * (A持仓数量/前1-10名总持仓数量)
        // A用户排名激励收益(排名内) = IP商城订单利润 * 瓜分收益比例 * (A持仓数量/前10-50名总持仓数量)
        // A用户交易激励收益 = IP商城订单利润 * 瓜分收益比例 * (A团队交易额/前1-50名总交易额)
        // 获取ip商城订单利润
        if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.POSITION_RANKING)) {
            settlementList(rankingBoardDetailsEvenNumber, rankingBoardConf, rankingBonusBillVO);
        } else if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.IP_MALL_TRADING)) {
            ipMallListSettlement(rankingBoardDetailsEvenNumber, rankingBoardConf, rankingBonusBillVO);
        } else if (rankingBoardConf.getType().equals(RankingBoardTypeEnum.NEW_POSITION_RANKING)) {
            newSettlementList(rankingBoardDetailsEvenNumber, rankingBoardConf, rankingBonusBillVO);
        }
        return rankingBonusBillVO;
    }
    private void newSettlementList(RankingBoardDetailsEvenNumber rankingBoardDetailsEvenNumber, RankingBoardConf rankingBoardConf, RankingBonusBillVO rankingBonusBillVO) {
        // 排行榜分润池
        MallRankingListPool residualPrizePool = mallRankingListPoolService.getResidualPrizePool();
        BigDecimal ipMallTradingProfit = residualPrizePool.getAmount();
        // 获取当前的排行榜,用户满足的条件.根据满足的条件来计算当前用户的收益.
        RankingBoardIncomeConf rankingBoardIncomeConf = rankingBoardIncomeConfDao.getByRankingBoardConfId(rankingBoardConf.getId(), rankingBoardDetailsEvenNumber.getRanking());

        if (BeanUtil.isNotEmpty(rankingBoardIncomeConf)) {
            if (rankingBoardIncomeConf.getBeginSection() + 1 <= rankingBoardDetailsEvenNumber.getRanking() && rankingBoardIncomeConf.getEndSection() >= rankingBoardDetailsEvenNumber.getRanking()) {
                rankingBonusBillVO.setIncomeName(rankingBoardIncomeConf.getIncomeName());
                // 获取到了满足用户收益以后,获取这个区间的总持仓数量.
                Integer totalHoldCount = rankingBoardConfDao.getBeginAndEndTotalHoldCount(rankingBoardConf.getLinkCollectionId(), rankingBoardConf.getBeginTime(), rankingBoardConf.getEndTime(), rankingBoardIncomeConf.getBeginSection(), rankingBoardIncomeConf.getEndSection());
                if (ipMallTradingProfit != null && NumberUtil.isGreaterOrEqual(ipMallTradingProfit, Convert.toBigDecimal(0))) {
                    // 计算当前用户的收益.
                    BigDecimal earnings = ipMallTradingProfit.multiply(rankingBoardIncomeConf.getIncomeProportion()).multiply((Convert.toBigDecimal(rankingBoardDetailsEvenNumber.getHoldCount()).divide(Convert.toBigDecimal(totalHoldCount), 8, BigDecimal.ROUND_DOWN))).setScale(2, BigDecimal.ROUND_DOWN);
                    rankingBonusBillVO.setAmount(earnings);
                    rankingBonusBillVO.setIncomeConfId(Convert.toStr(rankingBoardIncomeConf.getId()));
                }
            }
        }

        // 交易激励收益,有可能会有多个的情况出现.
        List<RankingBoardRewardsConf> tradingIncentiveEarnings = rankingBoardRewardsConfDao.getTradingIncentiveEarnings(rankingBoardConf.getId(), rankingBoardDetailsEvenNumber.getRanking());
        if (CollUtil.isEmpty(tradingIncentiveEarnings)) {
            rankingBonusBillVO.setLinkName(null);
        } else {
            StringJoiner stringJoiner = new StringJoiner(",");
            StringJoiner rewardsConfId = new StringJoiner(",");
            for (RankingBoardRewardsConf tradingIncentiveEarning : tradingIncentiveEarnings) {
                stringJoiner.add(StrUtil.format("{}*{}", tradingIncentiveEarning.getLinkName(), tradingIncentiveEarning.getLinkCount()));
                rewardsConfId.add(Convert.toStr(tradingIncentiveEarning.getId()));
            }
            rankingBonusBillVO.setLinkName(stringJoiner.toString());
            rankingBonusBillVO.setRewardsConfId(rewardsConfId.toString());
        }

        // 验证他是否是市值账号
        FilterIncomeList isTeamIncomeByUserId = filterIncomeListDao.getIsTeamIncomeByUserId(rankingBoardDetailsEvenNumber.getUserId());
        if (BeanUtil.isNotEmpty(isTeamIncomeByUserId)) {
            rankingBonusBillVO.setStatus(1);
        } else {
            rankingBonusBillVO.setStatus(0);
        }
    }

    private void ipMallListSettlement(RankingBoardDetailsEvenNumber rankingBoardDetailsEvenNumber, RankingBoardConf rankingBoardConf, RankingBonusBillVO rankingBonusBillVO) {
        // 排行榜分润池
        MallRankingListPool residualPrizePool = mallRankingListPoolService.getResidualPrizePool();
        BigDecimal ipMallTradingProfit = residualPrizePool.getAmount();
        // 获取当前的排行榜,用户满足的条件.根据满足的条件来计算当前用户的收益.
        RankingBoardIncomeConf rankingBoardIncomeConf = rankingBoardIncomeConfDao.getByRankingBoardConfId(rankingBoardConf.getId(), rankingBoardDetailsEvenNumber.getRanking());

        if (BeanUtil.isNotEmpty(rankingBoardIncomeConf)) {
            if (rankingBoardIncomeConf.getBeginSection() + 1 <= rankingBoardDetailsEvenNumber.getRanking() && rankingBoardIncomeConf.getEndSection() >= rankingBoardDetailsEvenNumber.getRanking()) {
//                获取个人交易额
                BigDecimal individualTurnover = rankingBoardConfDao.individualTurnover(rankingBoardDetailsEvenNumber.getUserId(), rankingBoardConf.getBeginTime(), rankingBoardConf.getEndTime());
                // 获取指定排名区间交易额
                BigDecimal turnover = rankingBoardConfDao.turnover(rankingBoardIncomeConf.getBeginSection(), rankingBoardIncomeConf.getEndSection(), rankingBoardConf.getBeginTime(), rankingBoardConf.getEndTime());
                // 分红
                BigDecimal shareOutBonus = ipMallTradingProfit.multiply(rankingBoardIncomeConf.getIncomeProportion()).multiply((individualTurnover.divide(turnover, 8, BigDecimal.ROUND_HALF_UP))).setScale(2, BigDecimal.ROUND_HALF_UP);
                rankingBonusBillVO.setAmount(shareOutBonus);
                rankingBonusBillVO.setIncomeConfId(Convert.toStr(rankingBoardIncomeConf.getId()));
            }
        }
        // 交易激励收益,有可能会有多个的情况出现.
        List<RankingBoardRewardsConf> tradingIncentiveEarnings = rankingBoardRewardsConfDao.getTradingIncentiveEarnings(rankingBoardConf.getId(), rankingBoardDetailsEvenNumber.getRanking());
        if (CollUtil.isEmpty(tradingIncentiveEarnings)) {
            rankingBonusBillVO.setLinkName(null);
        } else {
            StringJoiner stringJoiner = new StringJoiner(",");
            StringJoiner rewardsConfId = new StringJoiner(",");
            for (RankingBoardRewardsConf tradingIncentiveEarning : tradingIncentiveEarnings) {
                stringJoiner.add(StrUtil.format("{}*{}", tradingIncentiveEarning.getLinkName(), tradingIncentiveEarning.getLinkCount()));
                rewardsConfId.add(Convert.toStr(tradingIncentiveEarning.getId()));
            }
            rankingBonusBillVO.setLinkName(stringJoiner.toString());
            rankingBonusBillVO.setRewardsConfId(rewardsConfId.toString());
        }
        // 验证他是否是市值账号
        FilterIncomeList isTeamIncomeByUserId = filterIncomeListDao.getIsTeamIncomeByUserId(rankingBoardDetailsEvenNumber.getUserId());
        if (BeanUtil.isNotEmpty(isTeamIncomeByUserId)) {
            rankingBonusBillVO.setStatus(1);
        } else {
            rankingBonusBillVO.setStatus(0);
        }

    }


    private void settlementList(RankingBoardDetailsEvenNumber rankingBoardDetailsEvenNumber, RankingBoardConf rankingBoardConf, RankingBonusBillVO rankingBonusBillVO) {
        // 排行榜分润池
        MallRankingListPool residualPrizePool = mallRankingListPoolService.getResidualPrizePool();
        BigDecimal ipMallTradingProfit = residualPrizePool.getAmount();
        // 获取当前的排行榜,用户满足的条件.根据满足的条件来计算当前用户的收益.
        RankingBoardIncomeConf rankingBoardIncomeConf = rankingBoardIncomeConfDao.getByRankingBoardConfId(rankingBoardConf.getId(), rankingBoardDetailsEvenNumber.getRanking());

        if (BeanUtil.isNotEmpty(rankingBoardIncomeConf)) {
            if (rankingBoardIncomeConf.getBeginSection() + 1 <= rankingBoardDetailsEvenNumber.getRanking() && rankingBoardIncomeConf.getEndSection() >= rankingBoardDetailsEvenNumber.getRanking()) {
                rankingBonusBillVO.setIncomeName(rankingBoardIncomeConf.getIncomeName());
                // 获取到了满足用户收益以后,获取这个区间的总持仓数量.
                Integer totalHoldCount = rankingBoardConfDao.getTotalHoldCount(rankingBoardConf.getLinkCollectionId(), rankingBoardConf.getBeginTime(), rankingBoardConf.getEndTime(), rankingBoardIncomeConf.getBeginSection(), rankingBoardIncomeConf.getEndSection());
                if (ipMallTradingProfit != null && NumberUtil.isGreaterOrEqual(ipMallTradingProfit, Convert.toBigDecimal(0))) {
                    // 计算当前用户的收益.
                    BigDecimal earnings = ipMallTradingProfit.multiply(rankingBoardIncomeConf.getIncomeProportion()).multiply((Convert.toBigDecimal(rankingBoardDetailsEvenNumber.getHoldCount()).divide(Convert.toBigDecimal(totalHoldCount), 8, BigDecimal.ROUND_DOWN))).setScale(2, BigDecimal.ROUND_DOWN);
                    rankingBonusBillVO.setAmount(earnings);
                    rankingBonusBillVO.setIncomeConfId(Convert.toStr(rankingBoardIncomeConf.getId()));
                }
            }
        }

        // 交易激励收益,有可能会有多个的情况出现.
        List<RankingBoardRewardsConf> tradingIncentiveEarnings = rankingBoardRewardsConfDao.getTradingIncentiveEarnings(rankingBoardConf.getId(), rankingBoardDetailsEvenNumber.getRanking());
        if (CollUtil.isEmpty(tradingIncentiveEarnings)) {
            rankingBonusBillVO.setLinkName(null);
        } else {
            StringJoiner stringJoiner = new StringJoiner(",");
            StringJoiner rewardsConfId = new StringJoiner(",");
            for (RankingBoardRewardsConf tradingIncentiveEarning : tradingIncentiveEarnings) {
                stringJoiner.add(StrUtil.format("{}*{}", tradingIncentiveEarning.getLinkName(), tradingIncentiveEarning.getLinkCount()));
                rewardsConfId.add(Convert.toStr(tradingIncentiveEarning.getId()));
            }
            rankingBonusBillVO.setLinkName(stringJoiner.toString());
            rankingBonusBillVO.setRewardsConfId(rewardsConfId.toString());
        }

        // 验证他是否是市值账号
        FilterIncomeList isTeamIncomeByUserId = filterIncomeListDao.getIsTeamIncomeByUserId(rankingBoardDetailsEvenNumber.getUserId());
        if (BeanUtil.isNotEmpty(isTeamIncomeByUserId)) {
            rankingBonusBillVO.setStatus(1);
        } else {
            rankingBonusBillVO.setStatus(0);
        }
    }


    private void mallRanking(RankingBoardConf rankingBoardConf) {
        // 商城排行榜
        // 最小持仓数量
        Integer minimumQuantity = rankingBoardConf.getMinimumQuantity();
        // 榜单人数
        Integer listNumber = rankingBoardConf.getListNumber();
        // 开始时间
        Date startTime = rankingBoardConf.getBeginTime();
        // 结束时间
        Date endTime = rankingBoardConf.getEndTime();
        List<RankingBoardDetailsEvenNumber> rankingBoardDetailsEvenNumbers = new ArrayList<>();
        List<MallRanking> ranKing = rankingBoardConfDao.mallRanking(startTime, endTime, listNumber, minimumQuantity, rankingBoardConf.getId());
        for (MallRanking mallRanking : ranKing) {
            UserInfo userInfo = userInfoDao.getById(mallRanking.getUserId());
            RankingBoardDetailsEvenNumber rankingBoardDetailsEvenNumber = new RankingBoardDetailsEvenNumber();
            rankingBoardDetailsEvenNumber.setRankingBoardConfId(rankingBoardConf.getId());
            rankingBoardDetailsEvenNumber.setType(rankingBoardConf.getType());
            rankingBoardDetailsEvenNumber.setName(rankingBoardConf.getName());
            rankingBoardDetailsEvenNumber.setUserId(mallRanking.getUserId());
            rankingBoardDetailsEvenNumber.setCollectionId(rankingBoardConf.getLinkCollectionId());
            rankingBoardDetailsEvenNumber.setCollectionName(rankingBoardConf.getLinkColectionName());
            rankingBoardDetailsEvenNumber.setRanking(mallRanking.getRanks());
            rankingBoardDetailsEvenNumber.setHoldCount(mallRanking.getTotalRealPrice().setScale(2, BigDecimal.ROUND_DOWN).stripTrailingZeros().toPlainString());
            rankingBoardDetailsEvenNumber.setStatus(RankingBoardIncomeAndRewardsStatusEnum.UNISSUED);
            if (BeanUtil.isNotEmpty(userInfo)) {
                rankingBoardDetailsEvenNumber.setUserTel(userInfo.getUserTel());
                rankingBoardDetailsEvenNumber.setAvatarImg(userInfo.getAvatarImg());
                rankingBoardDetailsEvenNumber.setNickName(userInfo.getNickName());
                IdcardInfo byUserIdAndIsPass = idcardInfoDao.getByUserIdAndIsPass(userInfo.getId());
                if (BeanUtil.isNotEmpty(byUserIdAndIsPass)) {
                    rankingBoardDetailsEvenNumber.setIdcardName(byUserIdAndIsPass.getName());
                }
            }

            // 写入到集合中统一处理.
            rankingBoardDetailsEvenNumbers.add(rankingBoardDetailsEvenNumber);
        }
        if (CollUtil.isNotEmpty(rankingBoardDetailsEvenNumbers)) {
            batchOperation(rankingBoardConf, rankingBoardDetailsEvenNumbers);
        }
        rankingBoardConfDao.updateModifyTime(rankingBoardConf.getId());
    }

    private void collectionListRanking(RankingBoardConf rankingBoardConf) {
        // 藏品id.
        Long linkCollectionId = rankingBoardConf.getLinkCollectionId();
        // 最小持仓数量
        Integer minimumQuantity = rankingBoardConf.getMinimumQuantity();
        // 榜单人数
        Integer listNumber = rankingBoardConf.getListNumber();

        // 排名
        List<RanKingVO> ranKing = rankingBoardConfDao.getRanKing(linkCollectionId, minimumQuantity, listNumber, rankingBoardConf.getId());
        // 根据排名把奖励给查出来,有可能会有多个,每个排名都要查询两次.
        List<RankingBoardDetailsEvenNumber> rankingBoardDetailsEvenNumbers = new ArrayList<>();
        for (RanKingVO ranKingVO : ranKing) {
            UserInfo userInfo = userInfoDao.getById(ranKingVO.getUserId());
            RankingBoardDetailsEvenNumber rankingBoardDetailsEvenNumber = new RankingBoardDetailsEvenNumber();
            rankingBoardDetailsEvenNumber.setRankingBoardConfId(rankingBoardConf.getId());
            rankingBoardDetailsEvenNumber.setType(rankingBoardConf.getType());
            rankingBoardDetailsEvenNumber.setName(rankingBoardConf.getName());
            rankingBoardDetailsEvenNumber.setUserId(ranKingVO.getUserId());
            rankingBoardDetailsEvenNumber.setCollectionId(rankingBoardConf.getLinkCollectionId());
            rankingBoardDetailsEvenNumber.setCollectionName(rankingBoardConf.getLinkColectionName());
            rankingBoardDetailsEvenNumber.setRanking(ranKingVO.getRanks());
            rankingBoardDetailsEvenNumber.setHoldCount(Convert.toStr(ranKingVO.getCount()));
            rankingBoardDetailsEvenNumber.setStatus(RankingBoardIncomeAndRewardsStatusEnum.UNISSUED);
            if (BeanUtil.isNotEmpty(userInfo)) {
                rankingBoardDetailsEvenNumber.setUserTel(userInfo.getUserTel());
                rankingBoardDetailsEvenNumber.setAvatarImg(userInfo.getAvatarImg());
                rankingBoardDetailsEvenNumber.setNickName(userInfo.getNickName());
                IdcardInfo byUserIdAndIsPass = idcardInfoDao.getByUserIdAndIsPass(userInfo.getId());
                if (BeanUtil.isNotEmpty(byUserIdAndIsPass)) {
                    rankingBoardDetailsEvenNumber.setIdcardName(byUserIdAndIsPass.getName());
                }
            }

            // 把数据插入集合中,插入之前需要把另外一个表中的数据删除掉.
            rankingBoardDetailsEvenNumbers.add(rankingBoardDetailsEvenNumber);
        }
        if (CollUtil.isNotEmpty(rankingBoardDetailsEvenNumbers)) {
            batchOperation(rankingBoardConf, rankingBoardDetailsEvenNumbers);
        }
        rankingBoardConfDao.updateModifyTime(rankingBoardConf.getId());
    }

    private void batchOperation(RankingBoardConf rankingBoardConf, List<RankingBoardDetailsEvenNumber> rankingBoardDetailsEvenNumbers) {
        // 插入表,插入之前删除另外一张表的数据
        rankingBoardDetailsNumberDao.saveBath(rankingBoardDetailsEvenNumbers, tableSegmentation(Boolean.FALSE));
    }

    public ListDetailsListVO listDetailsListByUserId(Long id, Long userId) {
        /*
         * 1.根据规则获取表名
         * 2.根据表名获取数据
         * 3.如果获取不到数据,则翻转获取另外一个表的数据
         * 4.如果还是获取不到数据,则返回空
         */
        RankingBoardConf rankingBoardConf = rankingBoardConfDao.getById(id);
        if (BeanUtil.isEmpty(rankingBoardConf)) {
            throw new GlobalRunTimeException("榜单不存在");
        }
        ListDetailsListVO listDetailsListVOIPage;
        listDetailsListVOIPage = rankingBoardDetailsNumberDao.listDetailsListByUserId(id, userId, tableSegmentation(false));
        return listDetailsListVOIPage;
    }

    /**
     * 根据规则获取表名
     *
     * @return
     */
    public static String tableSegmentation(Boolean overturn) {
        int hours = new Date().getHours();
        // 判定是否翻转,如果翻转取模返奇数表,如果不翻转取模返偶数表
        if (overturn) {
            if (hours % 2 == 0) {
                return "sc_ranking_board_details_odd_number";
            } else {
                return "sc_ranking_board_details_even_number";
            }
        }

        // 不翻转
        if (hours % 2 == 0) {
            return "sc_ranking_board_details_even_number";
        } else {
            return "sc_ranking_board_details_odd_number";
        }

    }

}
